import kf_lib_v2_2 as lib
import gzip


import urllib2
import thread
import time

WX_base = "http://aviationweather.gov/adds/dataserver_current/current/%s.cache.csv.gz"
WX_ADDRESSES = dict(metar="metars", pirep="aircraftreports",  
                    taf="tafs",  airmet="airsigmets")
                    
                    
class weather:
    def __init__(self, forceDownload=True):
        
        
        self.avWeather={}
        print "Downloading weather: "
        for wxType, addy in WX_ADDRESSES.iteritems():
            thread.start_new_thread(self._download_and_unpack, (wxType, addy))
            
        while set(WX_ADDRESSES.keys()) - set(self.avWeather.keys()):
            time.sleep(.5)
        
        print "Done"
        
    def _download_and_unpack(self, wxType, addy):        
        #print "Downloading:", wxType,
        f_gz = urllib2.urlopen(WX_base % addy)
        
        lib.write_file_and_save("wx/" + addy + ".csv", f_gz.read(), 'wb')
        
        f = gzip.open("wx/" + addy + ".csv", 'rb')
        
        lib.write_file_and_save("wx/" + addy + ".csv", f.read(), 'wb')
        
        xl=lib.readExcelTable("wx/" + addy + ".csv")
        self.avWeather[wxType] = xl.readSheet('', 5)
        
        
        
        print wxType + ", ",